package com.deschen.security;

import com.deschen.security.core.vo.ResultVO;
import com.deschen.security.dao.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.xml.transform.Result;
import java.security.Principal;

/**
 * @Author deschen
 * @Create 2019/8/11
 * @Description
 * @Since 1.0.0
 */
@SpringBootApplication
@RestController
@Slf4j
public class Application {



    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private ProviderSignInUtils providerSignInUtils;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @GetMapping("/demo")
    public String getDemo() {

        return "demo";
    }

    @GetMapping("/")
    public String get() {

        return "登入成功";
    }

    @GetMapping("/me")
    @PreAuthorize("hasAuthority('write')")
    public ResultVO getUserDetail(Principal userDetails) {
        return new ResultVO().success(userDetails);
    }

    /**
     * 注册用户：qq扫码后注册
     * @param user
     * @return
     */
    @PostMapping("/register")
    public ResultVO registUser(User user, HttpServletRequest request
    ) {
        // 1 获取userId,用户唯一标识
        String userId = user.getUsername();
        // 2 查询userId在数据库是否存在（代码省略）

        // 3 不存在则保存数据库

        // 4 把注册得userId与QQ用户信息绑定
        providerSignInUtils.doPostSignUp(userId, new ServletWebRequest(request));

        return null;
    }

}
